package com.eqdd.yiqidian.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.bean.SelectBean;
import com.eqdd.yiqidian.rongyun.message.link.LinkMessage;
import com.eqdd.yiqidian.rongyun.message.mingpian.MingpianMessage;
import com.eqdd.yiqidian.ui.share.ShareEnterActivity;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.MediaMessageContent;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;
import rx.Observable;
import rx.Subscriber;

import static com.jrmf360.rylib.wallet.JrmfWalletClient.getApplicationContext;

/**
 * Created by lzh on 17-1-10.
 */

public class ShareUtil {

    private static final String defaultImg = "https://www.eqid.top:8009/image/EQD20171212151233.png";

    public static String getWorkCircleUrl(String workId, String guid) {
        return "https://www.eqidd.com/Friend/friend.html?workid=" + workId + "&guid=" + guid;
    }

    public static String BASE_ARTICLE_LINK = "https://www.eqidd.com/chuangkeApace/html/circleDetails.html?id=";

    public static String getArticleUrl(long articleId) {
        return BASE_ARTICLE_LINK + articleId;
    }

    public static void share2QQ(String url, String fileUrl) {
        shareTo(QQ.Name, url, fileUrl);
    }

    public static void share2WeiXin(String url, String fileUrl) {
        shareTo(Wechat.Name, url, fileUrl);
    }

    public static void share2Sina(String url, String fileUrl) {
        shareTo(SinaWeibo.Name, url, fileUrl);
    }

    public static void share(String platForm, ShareParams shareParams) {

        if (platForm.equals(QQ.Name)) {
            if (shareParams.getTitle() != null && shareParams.getTitle().length() > 30) {
                shareParams.setTitle(shareParams.getTitle().substring(0, 30));
            }

            if (shareParams.getText() != null && shareParams.getText().length() > 40) {
                shareParams.setText(shareParams.getText().substring(0, 40));
            }
        }


        JShareInterface.share(platForm, shareParams, new PlatActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                System.out.println("分享成功");
            }

            @Override
            public void onError(Platform platform, int i, int i1, Throwable throwable) {
                System.out.println("分享失败" + throwable.toString());
                if (platform.getName().equals(QQ.Name) || platform.getName().equals(QZone.Name)) {
                    ToastUtil.showShort("请安装QQ");
                } else if (platform.getName().equals(Wechat.Name) || platform.getName().equals(WechatFavorite.Name)
                        || platform.getName().equals(WechatMoments.Name)) {
                    ToastUtil.showShort("请安装Wechat");

                } else if (platform.getName().equals(SinaWeibo.Name)) {
                    ToastUtil.showShort("请安装微博");
                }
            }

            @Override
            public void onCancel(Platform platform, int i) {
                System.out.println("分享取消");
            }
        });
    }

    public static void shareTo(String platForm, String url, String fileUrl) {
        ShareParams shareParams = new ShareParams();
        shareParams.setShareType(Platform.SHARE_WEBPAGE);
        shareParams.setUrl(url);
        shareParams.setImageUrl(TextUtils.isEmpty(fileUrl) ? defaultImg : fileUrl);
        JShareInterface.share(platForm, shareParams, new PlatActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                System.out.println("分享成功");
            }

            @Override
            public void onError(Platform platform, int i, int i1, Throwable throwable) {
                System.out.println("分享失败" + throwable.toString());
                if (platform.getName().equals(QQ.Name)) {

                    ToastUtil.showShort("请安装QQ");
                } else if (platform.getName().equals(Wechat.Name)) {

                    ToastUtil.showShort("请安装Wechat");

                } else if (platform.getName().equals(SinaWeibo.Name)) {
                    ToastUtil.showShort("请安装微博");
                }
            }

            @Override
            public void onCancel(Platform platform, int i) {
                System.out.println("分享取消");
            }
        });
    }

    public static void share2QQ(String url) {
        share2QQ(url, defaultImg);
    }


    public static void share2EQDMessage(BaseActivity baseActivity, MessageContent messageContent) {
        AppConstent.messageContent = messageContent;
        baseActivity.startActivity(ShareEnterActivity.class);
    }

    public static void share2EQDImg(BaseActivity baseActivity, File imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*"); // 纯文本
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imgPath));
        intent.setComponent(new ComponentName("com.eqdd.yiqidian", "com.eqdd.yiqidian.ui.share.ShareEnterActivity"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        baseActivity.startActivity(intent);
    }

    public static void share2Sina(String url) {
        share2Sina(url, defaultImg);
    }

    public static void share2WeXin(String url) {
        share2WeiXin(url, defaultImg);
    }

    /**
     * 分享功能
     *
     * @param context       上下文
     * @param activityTitle Activity的名字
     * @param msgTitle      消息标题
     * @param msgText       消息内容
     */
    public static void shareMsgText(Context context, String activityTitle, String msgTitle, String msgText) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain"); // 纯文本
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }

    public static void shareMsgImage(Context context, String activityTitle, String msgTitle,
                                     String imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (imgPath == null || imgPath.equals("")) {
            intent.setType("text/plain"); // 纯文本
        } else {
            File f = new File(imgPath);
            if (f != null && f.exists() && f.isFile()) {
                intent.setType("image/*");
                Uri u = null;
                Uri myUri = Uri.fromFile(f);
                AppConstent.messageContent = ImageMessage.obtain(myUri, myUri);

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    u = FileProvider.getUriForFile(getApplicationContext(),
                            "com.eqdd.yiqidian.fileProvider", f);
                } else {
                    u = Uri.fromFile(f);
                }
//                 = Uri.fromFile(f);
                intent.putExtra(Intent.EXTRA_STREAM, u);
            }
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
//        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }

    public static void shareMsgImage(Context context, String activityTitle, String msgTitle,
                                     Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
//        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }


    public static void shareMsgVoice(Context context, String activityTitle, String msgTitle,
                                     File f) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (f != null && f.exists() && f.isFile()) {
            intent.setType("audio/*");
            Uri u = Uri.fromFile(f);
            intent.putExtra(Intent.EXTRA_STREAM, u);
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
//        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }

    public static void shareMsgVoice(Context context, String activityTitle, String msgTitle,
                                     Uri uri) {
        Intent intent = new Intent(Intent.ACTION_SEND);

        intent.setType("audio/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);

        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
//        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }

    public static final int TEXT = 1;
    public static final int IMAGE = 2;
    public static final int MULTI_IMAGE = 3;

    public static final int FROM_EQD = 1;
    public static final int FROM_OTHER = 2;
    public static final int FROM_EQD_GET = 3;

    public static void sendMyself(BaseActivity baseActivity, List<SelectBean> shareBeanList) {
        if (shareBeanList != null && shareBeanList.size() > 0) {
            baseActivity.showLoading();
            Observable.from(shareBeanList)
                    .subscribe(new Subscriber<SelectBean>() {
                        @Override
                        public void onCompleted() {
                            baseActivity.hideLoading();
                            ToastUtil.showShort("发送成功");
                            baseActivity.finish();
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(SelectBean shareBean) {
                            if (shareBean.getType() == Conversation.ConversationType.PRIVATE) {
                                RongIM.getInstance().refreshUserInfoCache(new UserInfo(shareBean.getGuid(), shareBean.getContent(), Uri.parse(shareBean.getHeadImg())));
                            }
                            if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof TextMessage ||
                                    AppConstent.messageContent instanceof RichContentMessage ||
                                    AppConstent.messageContent instanceof VoiceMessage)) {
                                Message myMessage = Message.obtain(shareBean.getGuid(), shareBean.getType(), AppConstent.messageContent);
                                RongIM.getInstance().sendMessage(myMessage, null, null, new IRongCallback.ISendMessageCallback() {
                                    @Override
                                    public void onAttached(Message message) {
                                        //消息本地数据库存储成功的回调
                                    }

                                    @Override
                                    public void onSuccess(Message message) {
                                        //消息通过网络发送成功的回调
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                        //消息发送失败的回调
                                        AppConstent.messageContent = null;
                                    }
                                });
                            } else if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof LocationMessage)) {
                                Message myMessage = Message.obtain(shareBean.getGuid(), shareBean.getType(), AppConstent.messageContent);
                                RongIM.getInstance().sendLocationMessage(myMessage, null, null, new IRongCallback.ISendMessageCallback() {
                                    @Override
                                    public void onAttached(Message message) {
                                        //消息本地数据库存储成功的回调
                                    }

                                    @Override
                                    public void onSuccess(Message message) {
                                        //消息通过网络发送成功的回调
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                        //消息发送失败的回调
                                        AppConstent.messageContent = null;
                                    }
                                });
                            } else if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof ImageMessage)) {
                                RongIM.getInstance().sendImageMessage(
                                        shareBean.getType(),
                                        shareBean.getGuid(), AppConstent.messageContent,
                                        null, null, new RongIMClient.SendImageMessageCallback() {

                                            @Override
                                            public void onAttached(Message message) {
                                                //保存数据库成功
                                            }

                                            @Override
                                            public void onError(Message message, RongIMClient.ErrorCode code) {
                                                //发送失败
                                                AppConstent.messageContent = null;
                                            }

                                            @Override
                                            public void onSuccess(Message message) {
                                                //发送成功
                                                AppConstent.messageContent = null;
                                            }

                                            @Override
                                            public void onProgress(Message message, int progress) {
                                                //发送进度
                                            }
                                        });
                            } else if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof MediaMessageContent)) {

                                Message myMessage = Message.obtain(shareBean.getGuid(), shareBean.getType(), AppConstent.messageContent);
                                RongIM.getInstance().sendMediaMessage(myMessage, null, null, new IRongCallback.ISendMediaMessageCallback() {
                                    @Override
                                    public void onProgress(Message message, int i) {

                                    }

                                    @Override
                                    public void onCanceled(Message message) {
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onAttached(Message message) {

                                    }

                                    @Override
                                    public void onSuccess(Message message) {
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                        AppConstent.messageContent = null;
                                    }
                                });
                            } else if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof MingpianMessage)) {

                                Message myMessage = Message.obtain(shareBean.getGuid(), shareBean.getType(), AppConstent.messageContent);
                                RongIM.getInstance().sendMessage(myMessage, null, null, new IRongCallback.ISendMessageCallback() {

                                    @Override
                                    public void onAttached(Message message) {

                                    }

                                    @Override
                                    public void onSuccess(Message message) {
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                        AppConstent.messageContent = null;
                                    }
                                });
                            } else if (AppConstent.messageContent != null && (AppConstent.messageContent instanceof LinkMessage)) {

                                Message myMessage = Message.obtain(shareBean.getGuid(), shareBean.getType(), AppConstent.messageContent);
                                RongIM.getInstance().sendMessage(myMessage, null, null, new IRongCallback.ISendMessageCallback() {

                                    @Override
                                    public void onAttached(Message message) {

                                    }

                                    @Override
                                    public void onSuccess(Message message) {
                                        AppConstent.messageContent = null;
                                    }

                                    @Override
                                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                                        AppConstent.messageContent = null;
                                    }
                                });
                            } else {
                                ToastUtil.showShort("不支持此类型");
                            }
                        }
                    });
        }

    }
}
